import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CoreModule } from './../core.module';
// import { NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { timeout } from 'rxjs/operators';
import { urlService } from './url';
import { Router, ActivatedRoute } from '@angular/router';
import { ToptipsService, ToptipsType } from 'ngx-weui/toptips';
import { StorageService } from '../sotrage/storage.service';
import { Location } from '@angular/common';
import { DialogConfig, DialogService } from 'ngx-weui';
import { I18nService } from '../i18n/i18n.service';

@Injectable({
    providedIn: CoreModule,
})
export class ApiService {
    msgData;
    constructor(
        private i: I18nService, 
        private srv: ToptipsService,
        private http: HttpClient,
        private sto: StorageService,
        private router: Router,
        private location: Location,
        private route: ActivatedRoute,
        private dialog: DialogService
    ) {
        this.i.get([
            'loginPage.model1',
            'loginPage.model2',
            'loginPage.model3',
            'loginPage.model4',
            'AGENCY-Page.confirm'
        ]).subscribe(res => {
			this.msgData = res;
			this.config = {
                title: res['loginPage.model1'],
                content: '',
                cancel: res['loginPage.model2'],
                confirm: res['AGENCY-Page.confirm'],
            };
            this.loginErrorNumConfig = {
                title: res['loginPage.model1'],
                content: res['loginPage.model3'],
                cancel: res['AGENCY-Page.confirm'],
                confirm: null,
            };
		});
     }

    get(url: string, params?: { [key: string]: any }, noFail?: Boolean): Promise<Function> {
        let header = this.getHeader(url);
        const request = this.http
            .get(urlService('dev', url), {
                params: params,
                headers: header
            })
            .pipe(timeout(240000))
            .toPromise();
        return new Promise((resolve, reject) => {
            request
                .then((res: any) => {
                    if (res.status === '0') {
                        resolve(res.data);
                    } else {
                        reject(res.data);
                        if (!noFail) {
                            this.srv.warn(res.message);
                        }
                    }
                    if (res.status === '1326') {
                        this.router.navigateByUrl('/login');
                    }
                })
                .catch(res => {
                    if (res.status === 403) {
                        sessionStorage.setItem('returnurl', this.router.url);
                        // this.srv.warn('登录超时，请重新登录');
                        this.router.navigateByUrl('/login');
                    } else {
                        this.srv.warn(this.msgData['loginPage.model4']);
                    }
                });
        });
    }

    config: DialogConfig = {
		title: '',
		content: '',
		cancel: '',
		confirm: '',
	};
    loginErrorNumConfig: DialogConfig = {
		title: '',
		content: '',
		confirm: '',
	};

    post(url: string, data?: { [key: string]: any }, params?: { [key: string]: any }, noFail?: Boolean, headers?: Headers, noValid?: Boolean): Promise<Function> {
        let header = this.getHeader(url);
        const request = this.http
            .post(urlService('dev', url), data, {
                params: params,
                headers: header
            })
            .pipe(timeout(60000))
            .toPromise();
        return new Promise((resolve, reject) => {
            request
                .then((res: any) => {
                    switch (res.status) {
                        case '0':
                            resolve(res);
                            break;
                        case '1332':
                            res['data']['loginErrorNum'] == '3' ?  this.dialog.show(this.loginErrorNumConfig).subscribe((res: any) => {
                            }) : '' ;
							reject(res);
                            break;
                        case '1331':
                                this.config.content = res.message;
                                this.dialog.show(this.config).subscribe((res: any) => {
                                    !res.value ? this.router.navigateByUrl('/updatePwd/3') : '';
                                });
                            break;
                        case '1326':
                            this.router.navigateByUrl('/login');
                            break;
                        default:
                            if (!noFail) {
                                this.srv.warn(res.message);
                            };
                            break;
                    }
                })
                .catch(res => {
                    if (res.status === 403) {
                        console.log(this.route);
                        if (!noValid) {
                            sessionStorage.setItem('returnurl', this.router.url);
                            this.router.navigateByUrl('/login');
                        } else {
                            reject(res);
                        }
                    } else {
                        this.srv.warn(this.msgData['loginPage.model4']);
                    }
                });
        });
    }


    getHeader(url) {
        let l = 'zh_CN';
        let token;
        let user = this.sto.get('user');
        let str = '登录生成图形验证码唯一id生成图形验证码发送邮箱验证码注册设置密码(首次设置密码)'
        switch (this.sto.get('lang')) {
            case 'zh':
                l = 'zh_CN'
                break;
            case 'en':
                l = 'en_US'
                break;
            case 'jp':
                l = 'ja_JP'
                break;
        }
        let header = { 'lang': l };
        user ? token = 'Bearer ' + user['token'] : '';
        str.indexOf(url) == -1 && user ? header['Authorization'] = token : null;

        return header;
    }

    msgSuccess(t) {
        this.srv.success(t);
    }

    msgEeeor(t) {
        this.srv.warn(t);
    }

}
